let collectedData = [];

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('collect').addEventListener('click', async () => {
        document.getElementById('collect').textContent = '采集中...';
        
        try {
            const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
            await chrome.scripting.executeScript({
                target: {tabId: tab.id},
                files: ['content.js']
            });
        } catch (error) {
            console.error('采集失败:', error);
            alert('采集失败，请重试！');
        } finally {
            document.getElementById('collect').textContent = '采集元素';
        }
    });

    document.getElementById('download').addEventListener('click', () => {
        if (collectedData.length === 0) {
            alert('没有数据可供下载！请先采集数据。');
            return;
        }
        downloadCSV(collectedData);
    });
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'COLLECTED_DATA') {
        collectedData = message.data;
        if (collectedData.length === 0) {
            alert('未找到任何数据，请确认页面上是否有相关元素！');
            return;
        }
        updateTable(collectedData);
        // 传入 collectedData 参数
        downloadCSV(collectedData);
    }
});

function updateTable(data) {
    const tbody = document.querySelector('#dataTable tbody');
    tbody.innerHTML = '';

    data.forEach((item, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td title="${item.title}">${item.title.substring(0, 50)}${item.title.length > 50 ? '...' : ''}</td>
            <td title="${item.link}">${item.link.substring(0, 50)}${item.link.length > 50 ? '...' : ''}</td>
            <td>${item.quantity}</td>
            <td>${item.price}</td>
        `;
        tbody.appendChild(row);
    });
}

function downloadCSV(data) {
    // CSV 表头添加好评率
    const headers = ['标题', '链接', '销量', '价格', '好评率'];
    const csvContent = [
        headers.join(','),
        ...data.map(item => [
            `"${item.title.replace(/"/g, '""')}"`,  // 处理标题中可能包含的引号
            `"${item.link}"`,
            `"${item.quantity}"`,
            `"${item.price}"`,
            `"${item.rating}"`  // 添加好评率数据
        ].join(','))
    ].join('\n');

    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '商品数据.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}